<template>
  <div class="container">
    <div class="background">
      <div class="form-container">
        <h2>账号登录</h2>
        <form @submit.prevent="handleSubmit">
          <label for="account">请输入账号</label>
          <el-input type="text" id="account" v-model="formData.account" placeholder="请输入账号" required style="margin-bottom: 10px;height: 45px;"/>

          <label for="password">请输入密码</label>
          <el-input type="password" id="password" v-model="formData.Upassword" placeholder="请输入密码" show-password style="margin-bottom: 25px;height: 45px;"/>
          <button type="submit">登录</button>
          <div class="terms">
            <label id="agreement">
              <input type="checkbox" id="terms" v-model="terms" style="width: 15px; height: 19px; margin-bottom: 0px;margin-right: 5px;"/>
              <span><strong class="tint">登录即代表您同意</strong><a href="/useragreement" target="_blank" class="bold">用户协议</a><strong class="tint"> 和
                </strong> <a href="/privacyclause" target="_blank" class="bold">隐私条款</a></span>
            </label>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, inject, reactive,onMounted  } from 'vue';  // 引入 ref
import {  nextTick,onBeforeUnmount  } from 'vue';
import { useRouter } from 'vue-router'; // 引入 useRouter
import type { FormInstance, FormRules } from 'element-plus'
import { pa } from 'element-plus/es/locales.mjs';
import CryptoJS from 'crypto-js';
// import axios from 'axios';
const axios = inject('axios') //注入 axios
// 顶部导航栏菜单选中索引
const activeIndex = ref('/login')
// 创建路由对象，用于编程式导航
const router = useRouter()
//生命变量
const curUserId = ref("");
const curUserName = ref("");
const curSessionId = ref('');

//表单数据
interface FormData {
  account: string;
  phone: string;
  Upassword: string;
}
// 表单数据
const formData = reactive<FormData>({
  account: '',
  Upassword: '',
  phone: '',
})
//同意用户协议
const terms = ref(false)

// 生命周期函数
onMounted(() => {
  // 页面创建相关逻辑
});
// WebSocket实例
let websock: WebSocket | null = null;

onBeforeUnmount(() => {
  websocketclose();
});

// WebSocket相关方法
const initWebSocket = (curUserId: string, sessionId: string) => {
    console.log("开始连接:"+curUserId+" | "+sessionId);
    
  websock = new WebSocket(`ws://localhost:8080/websocket/${curUserId}/${sessionId}`);
  websock.onopen = websocketonopen;
  websock.onerror = websocketonerror;
  websock.onmessage = websocketonmessage;
  websock.onclose = websocketclose;
};

const websocketonopen = () => {
  console.log("WebSocket连接成功");
};

const websocketonerror = (e: Event) => {
  console.log("WebSocket连接发生错误", e);
};

const websocketonmessage = (e: MessageEvent) => {
  let data = JSON.parse(e.data);
  if (Array.isArray(data)) {
    // 列表数据
    sessionList_already.value = data;
  } else {
    // 消息数据
    list.value.push(data);
  }
};

const websocketclose = (e?: CloseEvent) => {
    console.log("curUserId.value:"+curUserId.value);
    console.log("curSessionId.value:"+curSessionId.value);
    
  if (curUserId.value != null) {
    if (curSessionId.value != null) {
      initWebSocket(curUserId.value, curSessionId.value);
    } else {
      initWebSocket(curUserId.value, "99999999");
    }
  }
  console.log("connection closed", e);
};


//登录
const handleSubmit = async () => {
  if (!terms.value) {
    alert('请先同意用户协议和隐私条款');
    return;
  }
  try {
    console.log({
      account: formData.account,
      Upassword: formData.Upassword,
    });
    const response = await axios.post('http://localhost:8080/usertlogin', {
      account: formData.account,
      upassword: formData.Upassword,
    },{
      headers: {
        'Content-Type': 'application/json',
      }
    });
    //// 假设响应格式为 { code: number, message: string, token: string, userInfo: object }
    if (response.data.code === 200) {
     // 登录成功，将 token 加密后存储到本地存储中
     const token = response.data.token;
     console.log("登录返回数据："+JSON.stringify(response.data.user,null,2));
     
      // 使用一个密钥进行加密（务必保密，不要Hardcode在代码中）
      const secretKey = 'your_secret_key'; // 替换为一个安全的密钥
      const encryptedToken = CryptoJS.AES.encrypt(token, secretKey).toString(); // 加密
      curUserId.value = response.data.user.uid;
      curUserName.value = response.data.user.uname;
      getSessionListNot()// 获取未建立的会话列表
			sessionListAlready()// 获取已建立的会话列表
			startSession(99999999)// 启动会话，99999999 可能是一个默认会话或特殊的会话标识
      localStorage.setItem('token', encryptedToken); // 存储加密后的Token
      
      // 跳转到首页
      router.push('/');
    } else {
      alert(response.data.message || '登录失败'); //使用返回的错误信息
    }
  } catch (error) {
    console.error(error);
    console.log("error:"+error);
    
    alert('出现错误，请稍后重试');
  }

}
// 获取可建立会话列表
const getSessionListNot = () => {
  axios.get(`http://localhost:8080/Conversation/not?userId=${curUserId.value}`)
    .then(response => {
      if (response.data.code === -1) {
        return $message.error(response.data.errDesc);
      }
      sessionList_not.value = response.data.data;
    })
    .catch(error => {
      console.log(error);
    });
};
// 获取已存在的会话列表
const sessionListAlready = () => {
  axios.get(`http://localhost:8080/Conversation/already?userId=${curUserId.value}`)
    .then(response => {
      if (response.data.code === -1) {
        return $message.error(response.data.errDesc);
      }
      sessionList_already.value = response.data.data;
    })
    .catch(error => {
      console.log(error);
    });
};
// 开始会话
const startSession = (sessionId: string) => {
  if (websock !== null) {
    websock.close();
  }
  curSessionId.value = sessionId;
  initWebSocket(curUserId.value, sessionId);
  msgList(sessionId);
};
// 获取消息数据
const msgList = (sessionId: string) => {
  axios.get(`http://localhost:8080/getMessageList?sessionId=${sessionId}`)
    .then(response => {
      if (response.data.code === -1) {
        return $message.error(response.data.errDesc);
      }
      list.value = response.data.data;
      // 从新获取列表
      sessionListAlready();
    })
    .catch(error => {
      console.log(error);
    });
};

</script>

<style scoped>
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  /* background: linear-gradient(to right, #673ab7, #e91e63); */
  background-image: url('../../public/images/Userlogin.png');
  /* 设置背景图片大小 */
  background-size: cover;/* 填充整个容器 */
  position: relative;
}

.background {
  position: relative;
}

.form-container {
  background: rgba(255, 255, 255, 0.8); /* 半透明背景 */
  padding: 25px;
  height: 400px;
  border-radius: 10px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  width: 500px;
  backdrop-filter: blur(10px); /* 模糊效果 */
}

h2 {
  margin-bottom: 20px;
  text-align: center;
  margin-top: 20px;
}

label {
  margin: 10px 0 5px;
  display: block;
}

input {
  width: 100%;
  padding: 10px;
  margin-bottom: 15px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

button {
  width: 100%;
  padding: 10px;
  background-color: #673ab7;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

button:hover {
  background-color: #5e35b1;
}

#agreement {
  display: inline-block;
  width: 100%;
  margin-top: 65px;

}

.terms {
  text-align: center;
  margin-top: 0px;
}

.bold {
  font-weight: bold;
  color: black;
  /* 将文本设为黑色 */
}

.tint {
  color: #888;
  font-weight: normal;
}

.terms #terms {
  float: left;
  width: 25px;
  background-color: #5e35b1;
  /* 居中 */
  transform: center;
}

span {
  float: left;
}
</style>